import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Like } from '../matches/likes.entity';
import { Feed } from '../feeds/feed.entity';

@Injectable()
export class LikesService {
  constructor(
    @InjectRepository(Like)
    private likeRepository: Repository<Like>,
    @InjectRepository(Feed)
    private feedRepository: Repository<Feed>,
  ) {}

  // 为动态点赞或取消点赞
  async togglePostLike(userId: number, postId: number): Promise<{ liked: boolean; count: number }> {
    // 首先检查动态是否存在
    const feed = await this.feedRepository.findOne({ where: { id: postId } });
    if (!feed) {
      throw new Error('动态不存在');
    }

    // 查找是否已经点赞
    const existingLike = await this.likeRepository.findOne({
      where: { 
        likerUserId: userId,
        postId: postId
      }
    });

    let count = await this.likeRepository.count({ 
      where: { postId: postId } 
    });

    if (existingLike) {
      // 如果已经点赞，则取消点赞
      await this.likeRepository.remove(existingLike);
      count--;
      return { liked: false, count };
    } else {
      // 如果没有点赞，则添加点赞
      const newLike = this.likeRepository.create({
        likerUserId: userId,
        postId: postId,
        likedAt: new Date(),
        status: 'active'
      });
      await this.likeRepository.save(newLike);
      count++;
      return { liked: true, count };
    }
  }

  // 获取动态的点赞状态和数量
  async getPostLikeInfo(userId: number, postId: number): Promise<{ liked: boolean; count: number }> {
    // 获取点赞总数
    const count = await this.likeRepository.count({ 
      where: { postId: postId } 
    });

    // 检查当前用户是否已点赞
    const existingLike = await this.likeRepository.findOne({
      where: { 
        likerUserId: userId,
        postId: postId
      }
    });

    return { liked: !!existingLike, count };
  }
}